#include "TcpServer.hpp"
#include <memory>

static Response calculatorHelper(const Request &req)
{
    Response resp(0, 0, req._x, req._y, req._op);
    switch (req._op)
    {
    case '+':
        resp._result = req._x + req._y;
        break;
    case '-':
        resp._result = req._x - req._y;
        break;
    case '*':
        resp._result = req._x * req._y;
        break;
    case '/':
        if (req._y == 0)
            resp._code = 1;
        else
            resp._result = req._x / req._y;
        break;
    case '%':
        if (req._y == 0)
            resp._code = 2;
        else
            resp._result = req._x % req._y;
        break;
    default:
        resp._code = 3;
        break;
    }
    return resp;
}

void calculator(Connection *conn, std::string &request)
{
    logMessage(DEBUG, "calculator() been called, get a request: %s", request.c_str());
    // 1. 构建请求
    Request req;
    // 2. 反序列化
    if(!req.Deserialize(request)) return;
    // 3. 构建应答
    Response resp;
    // 4. 业务处理
    resp = calculatorHelper(req);
    // 5. 序列化
    std::string sendstr = resp.Serialize();
    // 6. 解决粘包问题
    sendstr = Encode(sendstr);
    // 7. 将处理后的应答交给服务器
    conn->_out_buffer += sendstr;
    // 8. 让服务器的 epoll 对象设置对写事件的关心
    conn->_tsvr->EnableReadWrite(conn, true, true);
}
int main()
{
    std::unique_ptr<TcpServer> svr(new TcpServer());
    svr->Dispather(calculator);
    return 0;
}
